<template>
  <view 
    class="draggable-item"
    :class="{ 'selected': isSelected }"
    :style="{
      left: x + 'px',
      top: y + 'px',
      backgroundColor: type === 'text' ? color : 'transparent',
      width: width + 'px',
      height: height + 'px',
      transform: `rotate(${itemRotation}deg)`
    }"
    @touchstart="handleTouchStart"
    @touchmove="handleTouchMove"
    @touchend="handleTouchEnd"
    @click.stop="handleClick"
  >
    <!-- 选中状态的边框 -->
    <view v-if="isSelected" class="selection-border"></view>
    
    <!-- 旋转按钮 -->
    <view 
      class="rotate-handle"
      @touchstart.stop="handleRotateStart"
      @touchmove.stop="handleRotateMove"
      @touchend.stop="handleRotateEnd"
    >
      <view class="rotate-icon">⟲</view>
    </view>

    <!-- 文本类型 -->
    <text v-if="type === 'text'" class="item-text">
      {{ content }}
    </text>
    
    <!-- 图片类型 -->
    <image 
      v-else-if="type === 'image'" 
      :src="content"
      class="item-image"
      mode="aspectFit"
    />
    
    <!-- 调整大小的手柄 -->
    <view 
      class="resize-handle"
      @touchstart.stop="handleResizeStart"
      @touchmove.stop="handleResizeMove"
      @touchend.stop="handleResizeEnd"
    ></view>
  </view>
</template>

<script setup>
import { defineProps, defineEmits, ref, watch } from 'vue'

// 定义props
const props = defineProps({
  x: {
    type: Number,
    required: true
  },
  y: {
    type: Number,
    required: true
  },
  color: {
    type: String,
    required: true
  },
  index: {
    type: Number,
    required: true
  },
  type: { 
    type: String, 
    required: true,
    validator: (value) => ['text', 'image'].includes(value)
  },
  content: { 
    type: String, 
    required: true 
  },
  isSelected: {
    type: Boolean,
    default: false
  },
  rotation: {  // 添加 rotation prop
    type: Number,
    default: 0
  }
})

// 定义事件
const emit = defineEmits(['dragStart', 'dragMove', 'dragEnd', 'resize', 'select', 'rotate'])

// 初始大小
const width = ref(100)
const height = ref(100)

// 调整大小相关状态
const isResizing = ref(false)
const resizeStartPos = ref({ x: 0, y: 0 })
const initialSize = ref({ width: 0, height: 0 })

// 添加旋转相关的状态
const itemRotation = ref(props.rotation)
const isRotating = ref(false)
const rotateCenter = ref({ x: 0, y: 0 })
const rotateStartAngle = ref(0)
const lastRotation = ref(0)

// 监听 rotation prop 的变化
watch(() => props.rotation, (newRotation) => {
  itemRotation.value = newRotation
})

// 计算角度的辅助函数
const calculateAngle = (center, point) => {
  const angle = Math.atan2(point.y - center.y, point.x - center.x) * 180 / Math.PI
  return angle < 0 ? angle + 360 : angle  // 确保角度在 0-360 范围内
}

// 触摸事件处理
const handleTouchStart = (event) => {
  emit('dragStart', { event, index: props.index })
}

const handleTouchMove = (event) => {
  emit('dragMove', { event, index: props.index })
}

const handleTouchEnd = () => {
  emit('dragEnd', { index: props.index })
}

// 调整大小的处理方法
const handleResizeStart = (event) => {
  isResizing.value = true
  const touch = event.touches[0]
  resizeStartPos.value = {
    x: touch.clientX,
    y: touch.clientY
  }
  initialSize.value = {
    width: width.value,
    height: height.value
  }
  event.preventDefault()
}

const handleResizeMove = (event) => {
  if (!isResizing.value) return
  
  const touch = event.touches[0]
  const deltaX = touch.clientX - resizeStartPos.value.x
  const deltaY = touch.clientY - resizeStartPos.value.y
  
  // 计算新的宽高，并设置最小值
  width.value = Math.max(50, initialSize.value.width + deltaX)
  height.value = Math.max(50, initialSize.value.height + deltaY)
  
  event.preventDefault()
}

const handleResizeEnd = () => {
  isResizing.value = false
  // 通知父组件大小变化
  emit('resize', { index: props.index, width: width.value, height: height.value })
}

// 旋转处理函数
const handleRotateStart = (event) => {
  isRotating.value = true
  const touch = event.touches[0]
  
  // 使用 uni-app 的方法获取元素位置
  const query = uni.createSelectorQuery()
  query.select('.draggable-item').boundingClientRect(data => {
    if (data) {
      // 计算元素中心点
      rotateCenter.value = {
        x: data.left + data.width / 2,
        y: data.top + data.height / 2
      }
      
      // 计算初始角度
      const touchAngle = calculateAngle(rotateCenter.value, {
        x: touch.clientX,
        y: touch.clientY
      })
      
      // 保存开始时的触摸角度
      rotateStartAngle.value = touchAngle
      
      // 记住当前的旋转角度
      lastRotation.value = itemRotation.value
    }
  }).exec()
}

const handleRotateMove = (event) => {
  if (!isRotating.value) return
  
  const touch = event.touches[0]
  const currentAngle = calculateAngle(rotateCenter.value, {
    x: touch.clientX,
    y: touch.clientY
  })
  
  // 计算角度差值
  let deltaAngle = currentAngle - rotateStartAngle.value
  
  // 防止角度突变
  if (deltaAngle > 180) deltaAngle -= 360
  if (deltaAngle < -180) deltaAngle += 360
  
  // 更新旋转角度
  itemRotation.value = lastRotation.value + deltaAngle
}

const handleRotateEnd = () => {
  if (isRotating.value) {
    isRotating.value = false
    // 更新内部旋转状态
    itemRotation.value = ((itemRotation.value % 360) + 360) % 360
    // 通知父组件旋转角度变化
    emit('rotate', { index: props.index, rotation: itemRotation.value })
  }
}

// 处理点击事件
const handleClick = (event) => {
  emit('select', { index: props.index })
  event.stopPropagation()
}
</script>

<style>
.draggable-item {
  position: absolute;
  border-radius: 8px;
  touch-action: none;
  cursor: move;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: visible; /* 改为 visible 以显示选中边框 */
}

/* 选中状态的边框样式 */
.selection-border {
  position: absolute;
  top: -2px;
  left: -2px;
  right: -2px;
  bottom: -2px;
  border: 2px solid sandybrown;
  border-radius: 10px;
  pointer-events: none;
}

/* 旋转按钮样式 */
.rotate-handle {
  position: absolute;
  right: 0;
  top: 0;
  width: 30px;
  height: 30px;
  background-color: rgba(0, 0, 0, 0.3);
  border-radius: 8px 8px 0 0;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  z-index: 1;
}

.rotate-icon {
  color: white;
  font-size: 20px;
  transform: rotate(0deg);
}

.item-text {
  color: #ffffff;
  font-size: 16px;
  text-align: center;
  padding: 10px;
}

.item-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.resize-handle {
  position: absolute;
  right: 0;
  bottom: 0;
  width: 30px;
  height: 30px;
  background-color: rgba(0, 0, 0, 0.3);
  border-radius: 0 0 8px 0;
  cursor: se-resize;
  background-image: linear-gradient(135deg, transparent 50%, rgba(255, 255, 255, 0.5) 50%);
}
</style> 